package file;

import java.nio.file.*;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        //define a folder root
        Path myDir = Paths.get("D:/test");

        try {
            WatchService watcher = myDir.getFileSystem().newWatchService();
            myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {
                // 阻塞方式，消费文件更改事件
                WatchKey watchKey = watcher.take();
                List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                for (WatchEvent<?> watchEvent : watchEvents) {
                    System.out.printf("[%s]文件发生了[%s]事件。%s %n", watchEvent
                            .context(), watchEvent.kind(), watchEvent.count());
                }
                boolean valid = watchKey.reset();
                if (!valid) break;
            }


        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}